#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date     : 2022-09-03 14:28:14
# @Author   : Jimy_Fengqi (jmps515@163.com)
# @Version  : V1.0
# @pyVersion: 3.8.1

from faulthandler import is_enabled
import sys, os, shutil
sys.path.insert(0, '../')
import xlwt
from xlutils.copy import copy
import json
from datetime import datetime, time
from threading import Thread
from util.log_handle import LogHandle
from util.string_handle import StringHandle
from util.json_handle import JSONHandle
from office.excel_handle import ExcelHandle

class MediaFile:
    enable = False
    fileName = ""
    kind = ""
    type = "unknown"
    dir = ""
    path = ""
    size = ""
    createTime = ""
    lastChangeTime = ""
    lastAtTime = ""

    def __init__(self, fileName, dir, headDir, kindList):
        self.fileName = fileName
        typeStrList = fileName.rsplit('.')
        self.type = typeStrList[len(typeStrList) - 1]
        self.dir = dir
        kind = dir.replace(headDir, '')
        self.kind = kind[1:]
        self.path = os.path.join(dir, fileName)

        self.size = os.path.getsize(self.path)
        # 获取创建时间，返回值是标准时间，需要转换
        self.createTime = StringHandle.get_FileCreateTime(self.path)
        # 获取最后修改时间，返回值是标准时间，需要转换
        self.lastChangeTime = StringHandle.get_FileModifyTime(self.path)
        # 获取访问时间，返回值是标准时间，需要转换
        self.lastAtTime = StringHandle.get_FileAccessTime(self.path)

        for i in range(0, len(kindList)):
            index = fileName.find(kindList[i])
            if index != -1 :
                self.enable = True
                break

class MediaConfig:
    mediaData = {}
    excelName = "MediaFileList"
    excelSavePath = "../data"
    logName = "find_media"
    logSavePath = "../log/find_media.log"

    def __init__(self, excelName):
        dt = datetime.now()
        self.excelSavePath = "../data/{}{}.xlsx".format(excelName, dt.strftime('%Y-%-m-%d'))

class Fiter:
    negwordDict = []
    keyword = []

    def __init__(self, neg_left_word, neg_right_word, keyword):
        self.neg_left_word = neg_left_word
        self.neg_right_word = neg_right_word
        self.keyword = keyword

def write_excel(name, dataConfig, head_data, dataList):
   # 表头内容填充(表格内容填充)
   wb = xlwt.Workbook()
   index = 0
   for data in dataConfig:
       # 填充文档
       sheetDataList=[]
       for i in range(1, len(dataList[index])):
           sheetRowList=[]
           sheetRowList.append(dataList[index][i].fileName)
           sheetRowList.append(dataList[index][i].kind)
           sheetRowList.append(dataList[index][i].type)
           sheetRowList.append(dataList[index][i].dir)
           sheetRowList.append(dataList[index][i].path)
           sheetRowList.append(dataList[index][i].size)
           sheetRowList.append(dataList[index][i].createTime)
           sheetRowList.append(dataList[index][i].lastChangeTime)
           sheetRowList.append(dataList[index][i].lastAtTime)
           sheetDataList.append(sheetRowList)
       ExcelHandle.add_sheet_data(wb, data["type"], head_data, sheetDataList)
       index += 1
   wb.save(name)

def get_filelist(dir, kindList, isShowDir = False):
    dataList = []
    for home, dirs, files in os.walk(dir):
        if isShowDir == True:
        # dataList.append("#######文件夹列表#######")
            for dir in dirs:
                dataList.append(dir)
        # dataList.append("#######文件夹列表#######")

        # dataList.append("#######文件列表#######")
        for filename in files:
            media = MediaFile(filename, home, dir, kindList)
            if media.enable:
                dataList.append(media)
            #######file list#######
        # dataList.append("#######file list#######")
    return dataList

# 写入Json 文件
def write_json_file(log, path, dataConfg, dataList, jsontext):
    fileDict = {}
    # for i in range(len(dataList)):
    # 填充文档
    # for k in range(0, len(dataConfg)):
    totalStr = ""
    for i in range(0, len(dataList)):
        for j in range(1, len(dataList[i])):
            if dataConfg[i]["isCheckOk"] is True:
                jsontext[dataConfg[i]["type"]].append({'fileName': dataList[i][j].fileName, 'kind': dataList[i][j].kind, 'type':dataList[i][j].type, 'dir': dataList[i][j].dir,'path': dataList[i][j].path})
                if dataConfg[i]["isCheckRepeatFile"] is True:
                    check_repeat_fileName(dataList[i][j], dataConfg[i]["sourceDir"], dataConfg[i]["sourceDir"], fileDict)
        totalStr.append(dataConfg[i]["type"] + ":").append(len(dataList[i])).append(" ")
    jsontext["total"] = totalStr
    JSONHandle.write_json_file(path, jsontext)
    log.comlog_info("媒体文件已生成，文件保存路径为：" + path)
    newDataList = []
    for key in fileDict.keys():
        index = 1
        for mediaFile in fileDict[key]:
            if len(fileDict[key]) != 1:
                print("当前重复文件已完成：%s %s %d" % (key, mediaFile.path, index) )
                if index != 1:
                    mediaFile.fileName = ""
                mediaFile.kind = ""
                mediaFile.type = ""
                mediaFile.dir = ""
                newDataList.append(mediaFile)
                index=2
    dataList.append(newDataList)
    repeat_head_data = ['文件名', '路径']
    # write_repeatedData_excel(excelPath, fileDict, 'repeated_photo', repeat_head_data)
    return True

# 检查路径
def check_fileName(fileName, dir):
    # 拆解文件名称
    fileType = ""
    newfile_path = ""
    typeIndex = fileName.rfind('.')
    if typeIndex == -1:
        fileType = fileName[typeIndex: ]
        fileName = fileName[0: typeIndex - 1]
    frontIndex = fileName.find('[')
    backIndex = fileName.find(']')
    keyIndex = fileName.find("www")
    file_path = os.path.join(dir, fileName) + fileType
    if backIndex != -1 and backIndex < len(fileName) - 1:
        if frontIndex != -1 and backIndex > frontIndex and keyIndex > frontIndex and keyIndex < backIndex:
            newfile_path = os.path.join(dir, fileName[0:frontIndex] + fileName[backIndex + 1:]) + fileType
        # 判断首位为单独中括号
        elif backIndex == 0 or (backIndex == -1 and frontIndex == 0):
            newfile_path = os.path.join(dir, fileName[1:]) + fileType

        if newfile_path:
            os.rename(file_path, newfile_path)
            print("文件替换已完成：%s %s->%s" % (fileName, file_path, newfile_path))

def check_repeat_fileName(mediaFile, targetDir, masterDir, fileDict):
    # 重复文件名查找
    if mediaFile.dir.find(targetDir) != -1:
        if len(fileDict) == 0 or not fileDict.__contains__(mediaFile.fileName):
            fileDict[mediaFile.fileName] = [mediaFile]
        else:
            fileDict[mediaFile.fileName].append(mediaFile)

def main(configPath):
    dataList = []
    vaild = True
    jsontext = {"total":{}}
    sync_config =  JSONHandle.read_json_file(configPath)  # default path "./config/sync_config.json"
    log = LogHandle(sync_config["log"]["name"], sync_config["log"]["savePath"])
    for data in sync_config["sourceData"]:
        if os.path.exists(data["sourceDir"]):
            jsontext[data["type"]] = []
            newDataList = get_filelist( data["sourceDir"], data["findFileType"])
            dataList.append(newDataList)
            log.comlog_info(str(data["type"]) + "文件检索已完成")
        else:
            data["isCheckOk"] = False
            log.comlog_warn(str(data["type"]) + "文件路径不存在")
            vaild = False
            break
    if vaild:
        saveExcelPath = "{}{}{}.xlsx".format(str(sync_config["excel"]["savePath"]), str(sync_config["excel"]["name"]), datetime.now().strftime('%Y-%m-%d_%H:%M:%S'))
        write_json_file(log, sync_config["outputPath"], sync_config["sourceData"], dataList, jsontext)
        write_excel(saveExcelPath, sync_config["sourceData"], sync_config["head_data"], dataList)
        log.comlog_info("文件查找已完成，相关记录已打印")
        # time.sleep(10)
        # shutil.copyfile(str(sync_config["outputPath"]), str(sync_config["backupPath"]))
    else:
        log.comlog_warn("文件比较失败，请检查相关配置文件是否正确")

# 文件解析和比较
if __name__ == "__main__":
    main("../config/sync_config.json")